package ru.dc;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ru.dc.object.CommandListener;
import ru.dc.object.HubEventListener;
import ru.dc.object.ServerInfo;
import ru.dc.object.commands.Command;
import ru.dc.object.commands.SR;
import ru.dc.object.events.hub.HubEvent;
import ru.dc.object.events.hub.SearchResultRecieved;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: deady
 * Date: 31.10.2010
 * Time: 22:10:39
 * To change this template use File | Settings | File Templates.
 */
public class ExternalEventsListener implements CommandListener {

    private List<HubEventListener> listeners = new ArrayList<HubEventListener>();
    private Log logger = LogFactory.getLog(getClass());

    public void commandRecieved(Command command) {
        if (command.getConnection()!=null) {//external
            return;
        }

        if (command instanceof SR) {
            SR sr = (SR) command;
            if (listeners.size()>0) {

                SearchResultRecieved e = new SearchResultRecieved();
                e.setDirectory(sr.isDirectory());
                e.setFilename(sr.getFilename());
                e.setFreeSlots(sr.getFreeSlots());
                e.setTotalSlots(sr.getTotalSlots());
                e.setHubname(sr.getHubname());
                e.setHubIp(sr.getHubIp());
                e.setPort(sr.getPort());
                e.setTargetNick(sr.getTargetNick());
                e.setSourceNick(sr.getSourceNick());
                ServerInfo hubInfo = Application.getApplication().getConnectionManager().findConnectionByAddress(sr.getHubIp()+":"+sr.getPort());
                e.setServerInfo(hubInfo);
                e.setSize(sr.getSize());
                fireHubEventOccured(e);
            }
            logger.debug("Recieved search results: "+sr);
        }
    }

    public void addEventListener(HubEventListener listener) {
        listeners.add(listener);
    }

    public void removeEventListener(HubEventListener listener) {
        listeners.remove(listener);
    }

    protected void fireHubEventOccured(HubEvent e) {
        for (HubEventListener listener :  listeners) {
            listener.onEvent(e);
        }
    }

}
